(function(window){
	var u = {};
	
	/**
     * table交互声明
     * @type {{}}
     */
    var vues = {};//map
	
	var isAnim = localStorage.getItem('isAnim') || '0';
	 
	/**
	 * 全局动画
	 */
	u.setAnim = function (el) {
		if ($(el).is(':checked')) {
			localStorage.setItem('isAnim', '0');
			isAnim = '0';
		} else {
			localStorage.setItem('isAnim', '1');
			isAnim = '1';
		}
	};
	
	
	/**
	 * 动画继承 全局动画关闭时依然可用
	 */
	 $.fn.extend({
		 anim: function (animationName) {
			 var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
			 $(this).addClass('animated ' + animationName).one(animationEnd, function () {
				 $(this).removeClass('animated ' + animationName);
			 });
		 }
	});
	 
	/**
	 * 动画继承 全局动画关闭时不可用，给内部js调用
	 */
	$.fn.extend({
		animateCss: function (animationName) {
			if (isAnim == '0') {
				var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
				$(this).addClass('animated ' + animationName).one(animationEnd, function () {
					$(this).removeClass('animated ' + animationName);
				});
			}
		}
	});
	
	/**
	 * 
	 */
	u.postJSON = function(url, data, successcallback,errcallback) {
        return jQuery.ajax({
            url:url,
            beforeSend: function(XMLHttpRequest) {
            	XMLHttpRequest.setRequestHeader("Content-Type","application/json;charset=utf-8");
            },
            type:"POST",
            dataType:"json",		
            data:JSON.stringify(data),
            success :successcallback,
            error:errcallback
        });
    };
    
    /**
     * 
     */
    u.postJSONCros = function(url, data, successcallback,errcallback) {
        return jQuery.ajax({
            url:url,
            beforeSend: function(XMLHttpRequest) {
            	XMLHttpRequest.setRequestHeader("Content-Type","application/json;charset=utf-8");
            },
            type:"POST",
            dataType:"json",		
            data:JSON.stringify(data),
            success :successcallback,
            error:errcallback
        });
    };
    
    u.getJSON = function(url, successcallback,errcallback) {
        return jQuery.ajax({
            url:url,
            type:"GET",
            success :successcallback,
            error:errcallback
        });
    };
    
    u.getJSONWithToken = function(url, successcallback,errcallback) {
        return jQuery.ajax({
            url:url,
            beforeSend: function(XMLHttpRequest) {
            	XMLHttpRequest.setRequestHeader("access_token",$.cookie("access_token"));
            	XMLHttpRequest.setRequestHeader("user_guid",$.cookie("user_guid"));
            },
            type:"GET",
            success :successcallback,
            error:errcallback
        });
    };
    
    u.getJSONWithCookies = function(url, successcallback) {
        return jQuery.ajax({
        	url:url,
        	type:"GET",
        	xhrFields: {
            	withCredentials: true
            },
            crossDomain: true,
            success :successcallback,
            error :function (data) {
            	layer.msg(data.responseJSON.message);
            }
        });
    };
    
    u.postJSONWithToken = function(url, data, successcallback, errcallback) {
        return jQuery.ajax({
            url:url,
            beforeSend: function(XMLHttpRequest) {
            	XMLHttpRequest.setRequestHeader("Content-Type","application/json;charset=utf-8");
            	XMLHttpRequest.setRequestHeader("access_token",$.cookie("access_token"));
            	XMLHttpRequest.setRequestHeader("user_guid",$.cookie("user_guid"));
            },
            type:"POST",
            dataType:"json",
            data:JSON.stringify(data),
            success :successcallback,
            error :errcallback
        });
    };
    
    u.getUrlParam = function (name) {
		 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
		 var r = window.location.search.substr(1).match(reg); //匹配目标参数
		 if (r != null) return unescape(r[2]); return null; //返回参数值
	};
    
	
    /**
     * 添加标签
     * @param tabId 标签ID
     * @param tabName 标签名
     * @param link 标签view地址
     * @param data 请求参数
     */
    u.openTab = function (tabId, tabName, link, data) {
        var $tab = $(tabId)[0];
        var tabId2 = tabId.substr(1);
        //判断加载还是直接打开
        if ($tab == null || $tab == undefined) {
            if (link != undefined && tabId != undefined && tabName != undefined) {
                $('#myTab li.active').removeClass('active');
                $('#myTabContent div.active').removeClass('active');
                
                $('#myTab ul:eq(0)').append('<li class="active"><a href="' + tabId + '" data-toggle="tab">' + tabName + '&nbsp; <i class="fa fa-times tab-close-btn"></i></a></li>');
                $('#myTabContent').append('<div class="tab-pane fade in active" id="' + tabId2 + '"><div></div></div>');
                var contentdiv = $('#myTabContent div.active div:eq(0)');
                if (isAnim) {
                    contentdiv.animateCss('fadeIn');
                }
                if (data) {
                    contentdiv.load(link, data, function (d) {
                        if (d) {
                            setTimeout(function () {
                                $(tabId).find('div:eq(0)').removeClass('fadeIn');
                            }, 950);
                        }
                    });
                } else {
                    contentdiv.load(link, function (d) {
                        if (d) {
                            setTimeout(function () {
                                $(tabId).find('div:eq(0)').removeClass('fadeIn');
                            }, 950);
                        }
                    });
                }
                u.resetCloseTab();
            }
        }
        u.ActiveTab(tabId);
    };
    
    
    /**
     * 设置选中页面
     * @param tabId
     * @constructor
     */
    u.ActiveTab = function (tabId) {
        //设置选择Tab页面
        $('#myTab a[href="' + tabId + '"]').tab('show');
    };
    
    /**
     * 绑定关闭事件
     * @param string
     * @param tabId
     */
    u.setCloseView = function (string, tabId) {
        $(string+":last").click(function () {
            u.CloseView(tabId);
        });
    };
    
    /**
     * 关闭窗口
     * @param tabId
     * @constructor
     */
    u.CloseView = function (tabId) {
        var a = $('#myTab a[href="#' + tabId + '"]');
        var prevlink = a.parent().prev().find('a');
        var prevlinkTab = prevlink.attr('href');
        if (prevlinkTab != null && prevlinkTab != '' && prevlinkTab != undefined) {
            prevlink.tab('show');
            $(prevlinkTab).addClass('active').addClass('in');
        }
        a.parent().remove();
        $('#' + tabId).remove();
    };
    
    /**
     * 重置关闭事件
     */
    u.resetCloseTab = function () {
        //绑定关闭事件
        $('#myTab span.fa-times-circle').click(function () {
            var tabId = $(this).parent().attr('href');
            var prevlink = $(this).parent().parent().prev().find('a');
            var prevlinkTab = prevlink.attr('href');
            if (prevlinkTab != null && prevlinkTab != '' && prevlinkTab != undefined) {
                prevlink.tab('show');
                $(prevlinkTab).addClass('active').addClass('in');
            }
            $(this).parent().parent().remove();
            $(tabId).remove();
        });
    };
    
    /**
     * string转json
     * @param str
     * @returns {*}
     */
    u.strToJson = function (str) {
        if (typeof str === 'string') {
            try {
                return JSON && JSON.parse(str);
            } catch (e) {
                return e;
            }
        } else {
            return str;
        }
    };
    
 
    u.showModal = function(title,url,area){
    	var index = layer.open({
			  type: 2, 
			  title: title,
			  maxmin: true, //开启最大化最小化按钮
			  area: area, //宽高
			  content: url //这里content是一个普通的String
		});
    };
    
    /**
     * 设置首页
     */
    u.setHome = function (url) {
        $("#home").load(url);
    };
    
    /**
     * 设置用户信息
     */
    u.setAccountInfo = function(data) {
    	$.cookie("user_guid", data.user.guid, { path: '/', expires: 10 });
    	$.cookie("is_admin", data.user.is_admin, { path: '/', expires: 10 });
    	$.cookie("username", data.user.username, { path: '/', expires: 10 });
    	$.cookie("name", data.user.name, { path: '/', expires: 10 });
    	$.cookie("access_token", data.token.access_token, {path: '/', expires: 10 });
    	$.cookie("top_dep_guid", data.user.top_dep_guid, {path: '/', expires: 10 });
    	$.cookie("top_dep_name", data.user.top_dep_name, {path: '/', expires: 10 });
    	$.cookie("dep_guid", data.user.dep_guid, {path: '/', expires: 10 });
    	$.cookie("is_superadmin", data.user.is_superadmin, {path: '/', expires: 10 });
    };
    
    /**
     * 设置cookie的值
     */
    u.getCookieValue = function (key) {
    	var value = $.cookie(key);
    	if(value){
    		return value;
    	}
    	return null;
    };
    
    /**
     * 登出时，清空cookies
     */
    u.clearAccountInfo = function(data) {
    	$.cookie('user_guid', '', { path: '/', expires: -1 });
    	$.cookie('username', '', { path: '/', expires: -1 });
    	$.cookie('name', '', { path: '/', expires: -1 });
    	$.cookie('access_token', '', { path: '/', expires: -1 });
    	$.cookie('is_admin', '', { path: '/', expires: -1 });
    	$.cookie('top_dep_guid', '', { path: '/', expires: -1 });
    	$.cookie('top_dep_name', '', { path: '/', expires: -1 });
    	$.cookie('dep_guid', '', { path: '/', expires: -1 });
    	$.cookie('is_superadmin', '', { path: '/', expires: -1 });
    };
    
    /**
     * 把from表单数据转成json格式
     * @frm 表单id
     */
    u.getFormJson = function(frm) {
	    var o = {};
	    var a = $(frm).serializeArray();
	    $.each(a, function () {
	        if (o[this.name] !== undefined) {
	            if (!o[this.name].push) {
	                o[this.name] = [o[this.name]];
	            }
	            o[this.name].push(this.value || '');
	        } else {
	            o[this.name] = this.value || '';
	        }
	    });
	    return o;
	}
    
	window.$byking = u;
})(window)
